<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<el-button type="success" @click="shopAddNewOrder" v-if="isAgent">新增订单</el-button>
			<!-- 新增按钮 -->
			<!-- <cl-add-btn /> -->
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />
			<!-- 导出按钮 -->
			<cl-export-btn :columns="Table?.columns" />
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<template #slot-zhongtian-order-btn="{ scope }">
					<el-button
						v-if="scope.row.orderProgress == 0"
						type="success"
						@click="
							() => {
								agentAddOrder(scope.row);
							}
						"
						>下单</el-button
					>
					<el-button
						v-else-if="scope.row.orderProgress == 1"
						type="warning"
						@click="
							() => {
								agentEditOrder(scope.row);
							}
						"
						>修改</el-button
					>
					<template
						v-else-if="
							scope.row.orderProgress == 2 ||
							scope.row.orderProgress == -1 ||
							scope.row.orderProgress == 1000
						"
					>
						<el-button
							type="primary"
							@click="
								() => {
									agentViewOrder(scope.row);
								}
							"
							>查看</el-button
						>
						<el-button
							type="danger"
							@click="
								() => {
									handleRefundExchange(scope.row);
								}
							"
							:disabled="
								new Date() - new Date(scope.row.shopOrderTime) >
									14 * 24 * 60 * 60 * 1000 &&
								!(scope.row.orderProgress == 3 || scope.row.orderProgress == 4)
							"
							>退换货</el-button
						>
						<!-- <el-button type="danger" v-if="scope.row.orderProgress == 1000">
							售后
						</el-button> -->
						<!-- <el-button
							type="info"
							@click="
								() => {
									handleCustomerRelationship(scope.row);
								}
							"
							v-if="scope.row.orderProgress != 1000"
							>客情处理</el-button
						> -->
						<el-button type="warning" v-if="scope.row.orderProgress == 1000"
							>售后</el-button
						>
					</template>
					<el-button
						v-else
						type="primary"
						@click="
							() => {
								agentViewOrder(scope.row);
							}
						"
						>查看</el-button
					>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="Upsert" />
	</cl-crud>
	<add-order :shopObj="shopObj" v-model="ShopaddOrderVisible" @closeDialog="closeDialog" />
	<shop-add-order
		v-model="ZhongtianAddOrderVisible"
		:orderObj="currentOrderObj"
		:order-id="currentOrderId"
		@closeDialog="closeDialog"
	/>
	<shop-view-order
		v-model="ZhongtianViewOrderVisible"
		:orderObj="currentOrderObj"
		:order-id="currentOrderId"
		@closeDialog="closeViewDialog"
	/>
	<!-- 退换货表单组件 -->
	<shop-refund-exchange
		v-model="RefundExchangeVisible"
		:orderObj="currentOrderObj"
		:order-id="currentOrderId"
		@closeDialog="closeRefundExchangeDialog"
	/>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'order-order'
});

import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { onMounted, reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import UserSelect from '/$/user/components/user-select.vue';
import { useBase } from '/$/base';
import ShopAddOrder from '../components/shop-add-order.vue';
import ShopViewOrder from '../components/shop-view-order.vue';
import AddOrder from '../components/add-order.vue';
import ShopRefundExchange from '../components/shop-refund-exchange.vue';

const { service } = useCool();
const { t } = useI18n();
const { user } = useBase();
const ZhongtianAddOrderVisible = ref(false);
const ZhongtianViewOrderVisible = ref(false);
const ShopaddOrderVisible = ref(false);
const RefundExchangeVisible = ref(false);
const currentOrderObj = ref({});
const currentOrderId = ref(0);
const shopObj = ref({});
const isAgent = ref(false);

onMounted(() => {
	service.order.order.createOrderBackendAuth().then((res) => {
		isAgent.value = res;
	});
});

// 选项
const options = reactive({
	payStatus: [
		{ label: t('待支付'), value: 0 },
		{ label: t('已支付'), value: 1 },
		{ label: t('支付失败'), value: 2 },
		{ label: t('已退款'), value: 3 }
	],
	deliveryStatus: [
		{ label: t('待发货'), value: 0 },
		{ label: t('已发货'), value: 1 },
		{ label: t('运输中'), value: 2 },
		{ label: t('已签收'), value: 3 },
		{ label: t('退货中'), value: 4 },
		{ label: t('已退货'), value: 5 }
	],
	payType: [
		{ label: t('微信支付'), value: 0 },
		{ label: t('线下'), value: 1 },
		{ label: t('银行卡'), value: 2 },
		{ label: t('其他'), value: 3 }
	],
	orderProgress: [
		{ label: t('审核不通过'), value: -1, type: 'error' },
		{ label: t('待门店下单'), value: 0, type: 'success' },
		{ label: t('待代理商下单'), value: 1, type: 'warning' },
		{ label: t('已下单厂家'), value: 2, type: 'primary' },
		{ label: t('退货审核中'), value: 3, type: 'error' },
		{ label: t('换货审核中'), value: 4, type: 'error' },
		{ label: t('退换货审核已通过'), value: 1000, type: 'success' }
	]
});

// cl-upsert
const Upsert = useUpsert({
	items: [
		{ label: t('选择用户'), prop: 'userId', component: { vm: UserSelect } },
		{
			label: t('订单号'),
			prop: 'orderNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('支付状态'),
			prop: 'payStatus',
			component: { name: 'el-radio-group', options: options.payStatus },
			value: 0,
			required: true
		},
		{
			label: t('物流状态'),
			prop: 'deliveryStatus',
			component: {
				name: 'cl-select',
				props: { options: options.deliveryStatus }
			},
			value: 0,
			span: 12,
			required: true
		},
		{
			label: t('支付方式'),
			prop: 'payType',
			component: { name: 'el-radio-group', options: options.payType },
			value: 0,
			required: true
		},
		{
			label: t('微信支付码'),
			prop: 'wechatPayCode',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('支付截图'),
			prop: 'payScreenshot',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('总金额'),
			prop: 'totalAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('优惠金额'),
			prop: 'discountAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('支付金额'),
			prop: 'payAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('备注'),
			prop: 'remark',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择商品'),
			prop: 'GoodIds',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('商品详情'),
			prop: 'productDetails',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('优惠详情'),
			prop: 'discountDetails',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择商品'),
			prop: 'GoodIds',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('商品详情'),
			prop: 'productDetails',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('优惠详情'),
			prop: 'discountDetails',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('下单时间'),
			prop: 'orderTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('支付时间'),
			prop: 'payTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('收货地址'),
			prop: 'address',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('收货人'),
			prop: 'consignee',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('联系电话'),
			prop: 'phone',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('支付截图'),
			prop: 'payImg',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择微信支付商户号'),
			prop: 'mchId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择微信支付订单号'),
			prop: 'transactionId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择微信支付预支付'),
			prop: 'prepayId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('微信支付二维码链接'),
			prop: 'codeUrl',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('微信支付H5链接'),
			prop: 'h5Url',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('微信支付小程序支付参数'),
			prop: 'miniPayParams',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('支付失败原因'),
			prop: 'failReason',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('退款金额'),
			prop: 'refundAmount',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('退款时间'),
			prop: 'refundTime',
			component: {
				name: 'el-date-picker',
				props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
			},
			span: 12
		},
		{
			label: t('退款单号'),
			prop: 'refundNo',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12
		},
		{
			label: t('选择店铺'),
			prop: 'shopId',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		}
	]
});

// cl-table
const Table = useTable({
	columns: [
		{ label: t('ID'), prop: 'id', minWidth: 80 },
		{ label: t('店铺'), prop: 'shopName', minWidth: 120 },
		{ label: t('销售'), prop: 'adminName', minWidth: 120 },
		{ label: t('用户'), prop: 'userNickName', minWidth: 120 },
		{ label: t('手机号'), prop: 'userPhone', minWidth: 120 },
		{ label: t('订单号'), prop: 'orderNo', minWidth: 120 },
		{
			label: t('支付状态'),
			prop: 'payStatus',
			minWidth: 120,
			dict: options.payStatus
		},
		// {
		// 	label: t("物流状态"),
		// 	prop: "deliveryStatus",
		// 	minWidth: 120,
		// 	dict: options.deliveryStatus,
		// },
		{
			label: t('支付方式'),
			prop: 'payType',
			minWidth: 120,
			dict: options.payType
		},
		// { label: t("微信支付码"), prop: "wechatPayCode", minWidth: 120 },
		// { label: t("支付截图"), prop: "payScreenshot", minWidth: 120 },
		{ label: t('总金额'), prop: 'totalAmount', minWidth: 120 },
		{ label: t('优惠金额'), prop: 'discountAmount', minWidth: 120 },
		{ label: t('支付金额'), prop: 'payAmount', minWidth: 120 },
		// { label: t("备注"), prop: "remark", minWidth: 120 },
		// { label: t("商品IDS"), prop: "GoodIds", minWidth: 120 },
		// { label: t("商品详情"), prop: "productDetails", minWidth: 120 },
		// { label: t("优惠详情"), prop: "discountDetails", minWidth: 120 },
		// {
		// 	label: t("下单时间"),
		// 	prop: "orderTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		// {
		// 	label: t("支付时间"),
		// 	prop: "payTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		// { label: t("收货地址"), prop: "address", minWidth: 120 },
		// { label: t("收货人"), prop: "consignee", minWidth: 120 },
		// { label: t("联系电话"), prop: "phone", minWidth: 120 },
		// { label: t("支付截图"), prop: "payImg", minWidth: 120 },
		// { label: t("微信支付商户号"), prop: "mchId", minWidth: 120 },
		// { label: t("微信支付订单号"), prop: "transactionId", minWidth: 120 },
		// { label: t("微信支付预支付ID"), prop: "prepayId", minWidth: 120 },
		// { label: t("微信支付二维码链接"), prop: "codeUrl", minWidth: 120 },
		// { label: t("微信支付H5链接"), prop: "h5Url", minWidth: 120 },
		// {
		// 	label: t("微信支付小程序支付参数"),
		// 	prop: "miniPayParams",
		// 	minWidth: 120,
		// },
		// { label: t("支付失败原因"), prop: "failReason", minWidth: 120 },
		// { label: t("退款金额"), prop: "refundAmount", minWidth: 120 },
		// {
		// 	label: t("退款时间"),
		// 	prop: "refundTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		// { label: t("退款单号"), prop: "refundNo", minWidth: 120 },
		// { label: t("店铺ID"), prop: "shopId", minWidth: 120 },
		{
			label: t('创建时间'),
			prop: 'createTime',
			minWidth: 170,
			component: { name: 'cl-date-text' }
		},
		{
			label: t('订单状态'),
			prop: 'orderProgress',
			minWidth: 120,
			dict: options.orderProgress
		},
		// {
		// 	label: t("更新时间"),
		// 	prop: "updateTime",
		// 	minWidth: 170,
		// 	sortable: "custom",
		// 	component: { name: "cl-date-text" },
		// },
		{ type: 'op', buttons: ['slot-zhongtian-order-btn'] }
	]
});

// cl-search
const Search = useSearch({
	// items: [
	// 	{
	// 		prop: 'orderProgress',
	// 		component: {
	// 			name: 'cl-select',
	// 			props: { options: options.orderProgress, placeholder: '订单状态' }
	// 		}
	// 	}
	// ]
});

// cl-crud
const Crud = useCrud(
	{
		service: service.order.order,
		async onRefresh(params, { next, done, render }) {
			if (!params.payStatus) {
				params.payStatus = 1;
			}
			console.log(user.info);
			params.shopId = user.info?.shopId || 0;
			// 如果shopId是4，则能查看4567的订单
			if (params.shopId == 4) {
				params.shopId = [4, 5, 6, 7];
			}
			Crud.value.params.payStatus = params.payStatus;
			Crud.value.params.orderProcess = params.orderProcess;
			Crud.value.params.isAgent = params.isAgent;
			const { list } = await next(params);
			// 渲染数据
			render(list);
		}
	},
	app => {
		app.refresh();
	}
);

function agentAddOrder(row) {
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	ZhongtianAddOrderVisible.value = true;
	// console.log('agnetAddOrder', currentOrderObj.value, row, row.orderNo)
}

function agentEditOrder(row) {
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	ZhongtianAddOrderVisible.value = true;
}

function agentViewOrder(row) {
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	ZhongtianViewOrderVisible.value = true;
}

function handleRefundExchange(row) {
	// 处理退换货逻辑
	console.log('处理退换货', row);
	currentOrderId.value = row.id;
	currentOrderObj.value = row;
	// 打开退换货弹窗
	RefundExchangeVisible.value = true;
}

async function viewZhongtianOrder(row) {
	const result = await service.order.merchant.queryOrder({
		order_id: row.id
	});
	console.log(result);
}

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}

function closeDialog() {
	ZhongtianAddOrderVisible.value = false;
	ShopaddOrderVisible.value = false;
	refresh();
}
function closeViewDialog() {
	ZhongtianViewOrderVisible.value = false;
}

function closeRefundExchangeDialog() {
	RefundExchangeVisible.value = false;
}

function shopAddNewOrder() {
	console.log('normalOrder');
	try {
		service.agent.agent.getAgentShopList({}).then(res => {
			if (res != null && res != '') {
				shopObj.value = res[0];
			} else {
				ElMessage.error('请先添加店铺');
			}
		});
		console.log('shopObj', shopObj.value);
		ShopaddOrderVisible.value = true;
	} catch (error) {
		console.log(error);
		ElMessage.error('亲，您暂无权限');
	}
}

// 监听RefundExchangeVisible.value变化，当为false时执行refresh方法
watch(
	() => RefundExchangeVisible.value,
	(newValue, oldValue) => {
		// 确保是数值变化并且新值为false
		if (newValue !== oldValue && newValue === false) {
			refresh();
		}
	}
);
</script>
